<!-- 字典数据 -->
<template>
  <div class="app-container">
	<div class="app-layout">
		<div class="pane" style="width: 100%;">
			<div class="head">
				<span>字典数据列表</span>
			</div>
			<div class="body">
				<div class="table-tool-bar">
					<div>
						<el-button type="primary" icon="plus" @click="handleOpenDialog()">新增</el-button>
						<el-button type="danger" :disabled="ids.length === 0" icon="delete" @click="handleDelete()">
						  删除
						</el-button>
					</div>
					<div>
						<el-input
						  v-model="queryParams.keywords"
						  style="width:320px"
						  placeholder="输入字典标签或值进行搜索"
						  class="input-with-select"
						>
						  <template #append>
							<el-button icon="search"  @click="handleQuery" />
						  </template>
						</el-input>
					</div>
				</div>
				<div>
					<el-table
					  v-loading="loading"
					  highlight-current-row
					  :data="tableData"
					  border
					  height="calc(100vh - 260px)"
					  @selection-change="handleSelectionChange"
					>
					  <el-table-column type="selection" width="55" align="center" />
					  <el-table-column label="字典标签" prop="name" />
					  <el-table-column label="字典值" prop="value" />
					  <el-table-column label="排序" prop="sort" />
					  <el-table-column label="状态">
					    <template #default="scope">
					      <el-tag :type="scope.row.status === '1' ? 'success' : 'info'">
					        {{ scope.row.status === '1' ? "启用" : "禁用" }}
					      </el-tag>
					    </template>
					  </el-table-column>
					
					  <el-table-column fixed="right" label="操作" align="center" width="220">
					    <template #default="scope">
					      <el-button
					        type="primary"
					        link
					        size="small"
					        icon="edit"
					        @click.stop="handleOpenDialog(scope.row)"
					      >
					        编辑
					      </el-button>
					      <el-button
					        type="danger"
					        link
					        size="small"
					        icon="delete"
					        @click.stop="handleDelete(scope.row.id)"
					      >
					        删除
					      </el-button>
					    </template>
					  </el-table-column>
					</el-table>
					<div style="display: flex;justify-content: flex-end;align-items: center">
						<pagination
						  v-model:total="total"
						  v-model:page="queryParams.cur"
						  v-model:limit="queryParams.limit"
						  @pagination="handleQuery"
						/>
					</div>
				</div>
			</div>
		</div>
	</div>

    <!--字典弹窗-->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="820px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="computedRules" label-width="100px">
        <el-card shadow="never">
          <el-form-item label="字典标签" prop="name">
            <el-input v-model="formData.name" placeholder="请输入字典标签" />
          </el-form-item>
          <el-form-item label="字典值" prop="value">
            <el-input v-model="formData.value" placeholder="请输入字典值" />
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="formData.status">
              <el-radio :value="'1'">启用</el-radio>
              <el-radio :value="'0'">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="排序">
            <el-input-number v-model="formData.sort" controls-position="right" />
          </el-form-item>
          <el-form-item label="标签类型">
            <el-tag v-if="formData.tagType" :type="formData.tagType" class="mr-2">
              {{ formData.name }}
            </el-tag>
            <el-radio-group v-model="formData.tagType">
              <el-radio value="success" border size="small">success</el-radio>
              <el-radio value="warning" border size="small">warning</el-radio>
              <el-radio value="info" border size="small">info</el-radio>
              <el-radio value="primary" border size="small">primary</el-radio>
              <el-radio value="danger" border size="small">danger</el-radio>
              <el-radio value="" border size="small">清空</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmitClick">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "DictData",
  inherititems: false,
});

import DictDataAPI, {
  DictDataPageQuery,
  DictDataPageVO,
  DictDataForm,
} from "@/api/system/dict-data";

const route = useRoute();

const dictId = ref(route.query.id as string);

const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<DictDataPageQuery>({
  cur: 1,
  limit: 10,
  dictId: dictId.value,
});

const tableData = ref<DictDataPageVO[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<any>({});

// 监听路由参数变化，更新字典数据
watch(
  () => [route.query.id],
  ([newDictCode]) => {
    queryParams.dictId = newDictCode as string;
    dictId.value = newDictCode as string;
    handleQuery();
  }
);
const computedRules = computed(() => {
  const rules: Partial<Record<string, any>> = {
    value: [{ required: true, message: "请输入字典值", trigger: "blur" }],
    name: [{ required: true, message: "请输入字典标签", trigger: "blur" }],
  };
  return rules;
});

// 查询
function handleQuery() {
  loading.value = true;
  DictDataAPI.getPage(queryParams)
    .then((data) => {
      tableData.value = data.list;
      total.value = data.totalRow;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryParams.cur = 1;
  handleQuery();
}

// 行选择
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 打开弹窗
function handleOpenDialog(row?: DictDataPageVO) {
  dialog.visible = true;
  dialog.title = row ? "编辑字典数据" : "新增字典数据";

  if (row?.id) {
    Object.assign(formData, row);
  }
}

// 提交表单
function handleSubmitClick() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = true;
      const id = formData.id;
      formData.dictId = dictId.value;
      if (id) {
        DictDataAPI.save({
			id:formData.id,
			dictId:formData.dictId,
			name:formData.name,
			value:formData.value,
			sort:formData.sort,
			status:formData.status,
			remark:formData.remark
		})
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        DictDataAPI.save({
			id:formData.id,
			dictId:formData.dictId,
			name:formData.name,
			value:formData.value,
			sort:formData.sort,
			status:formData.status,
			remark:formData.remark
		})
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;

  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
  formData.sort = 1;
  formData.status = '1';
}
/**
 * 删除字典
 *
 * @param id 字典ID
 */
function handleDelete(id?: number) {
  const attrGroupIds = [id || ids.value].join(",");
  if (!attrGroupIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      DictDataAPI.deleteByIds(attrGroupIds).then(() => {
        ElMessage.success("删除成功");
        handleResetQuery();
      });
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
	.left{
		width: 320px;
		margin-right: 10px;
	}
	.right{
		width: calc(100% - 220px);
	}
	.table-tool-bar{
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 5px;
	}
	:deep(.el-table th.el-table__cell) {
		/* background-color: #fafafa; */
		background-color: #eee;
		background-image: url();
		background-image: -webkit-linear-gradient(top, #f2f2f2 0, #fafafa 100%);
		background-image: -moz-linear-gradient(top, #f2f2f2 0, #fafafa 100%);
		background-image: -o-linear-gradient(top, #f2f2f2 0, #fafafa 100%);
		background-image: linear-gradient(to bottom, #f2f2f2 0, #fafafa 100%);
		font-size: 12px;
	}
</style>
